package com.ts.audiocamera

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.hardware.camera2.CameraCharacteristics
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.util.Size
import android.widget.Button
import android.widget.RelativeLayout
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.ts.camera2.Camera2Wrapper
import com.ts.camera2.TsCamera.GLCameraSurfaceView
import com.ts.camera2.camera.Camera2FrameCallback
import com.ts.camera2.camera.CameraUtil

class Camera2Activity : AppCompatActivity(),Camera2FrameCallback{


    var mGLCameraSurfaceView: GLCameraSurfaceView?=null;
    var mCamera2Wrapper: com.ts.camera2.camera.Camera2Wrapper?=null
    var CAMERA_PERMISSION_REQUEST_CODE=12;

//    var surfaceView:SurfaceView?= null
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_camera2)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
// 检查相机权限
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
            // 权限未授予，请求权限
            ActivityCompat.requestPermissions(this,
                arrayOf(Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO), CAMERA_PERMISSION_REQUEST_CODE)
        } else {
            // 权限已授予，打开摄像头
        }

    mGLCameraSurfaceView=findViewById(R.id.surface_view)
    mCamera2Wrapper=com.ts.camera2.camera.Camera2Wrapper(this)
    findViewById<Button>(R.id.capture).setOnClickListener {
        mCamera2Wrapper?.capture()
    }


    findViewById<Button>(R.id.front).setOnClickListener {
        val cameraId = mCamera2Wrapper!!.getCameraId()
        val cameraIds = mCamera2Wrapper!!.getSupportCameraIds()
        if (cameraIds != null) {
            for (i in cameraIds.indices) {
                if (cameraIds[i] != cameraId) {
                    mCamera2Wrapper?.updateCameraId(cameraIds[i])
                    updateTransformMatrix(cameraIds[i])
                    updateGLSurfaceViewSize(mCamera2Wrapper!!.getPreviewSize())
                    break
                }
            }
        }


    }
    }

    override fun onPause() {
        super.onPause()
        mCamera2Wrapper?.stopCamera()
    }

    override fun onResume() {
        super.onResume()
        mCamera2Wrapper?.startCamera()
        mCamera2Wrapper?.mCameraId?.let { updateTransformMatrix(it) };

       updateGLSurfaceViewSize(mCamera2Wrapper?.getPreviewSize()!!);
    }

    fun updateTransformMatrix(cameraId: String) {
        Log.e(TAG,"updateTransformMatrix"+cameraId)
        if (cameraId.toInt() == CameraCharacteristics.LENS_FACING_FRONT) {
            mGLCameraSurfaceView?.setTransformMatrix(90, 0)
        } else {
            mGLCameraSurfaceView?.setTransformMatrix(90, 1)
        }
    }


    fun updateGLSurfaceViewSize(previewSize: Size) {
        var fitSize: Size? = null
        Log.e(TAG,previewSize.width.toString()+"--"+previewSize.height.toString())
        fitSize = getScreenSize()?.width?.let {
            getScreenSize()?.height?.let { it1 ->
                CameraUtil.getFitInScreenSize(
                    previewSize.width,
                    previewSize.height,
                    it,
                    it1
                )
            }
        }
        val params = mGLCameraSurfaceView?.layoutParams as RelativeLayout.LayoutParams
        params?.width = fitSize?.width!!
        params?.height = fitSize?.height!!
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP or RelativeLayout.CENTER_HORIZONTAL)

        mGLCameraSurfaceView?.setLayoutParams(params)
    }
    protected var mRootViewSize: Size? = null
    protected var mScreenSize:android.util.Size? = null
    fun getScreenSize(): Size? {
        if (mScreenSize == null) {
            val displayMetrics = DisplayMetrics()
            windowManager.defaultDisplay.getMetrics(displayMetrics)
            mScreenSize = Size(displayMetrics.widthPixels, displayMetrics.heightPixels)
        }
        return mScreenSize
    }

    private  val TAG = "Camera2Activity"

    override fun onPreviewFrame(data: ByteArray?, width: Int, height: Int) {
//        Log.d(TAG,
//            "onPreviewFrame() called with: data = [$data], width = [$width], height = [$height]")

        if (data != null) {
            mGLCameraSurfaceView?.setImageData(data,width,height)
            mGLCameraSurfaceView?.requestRender()
        }

    }

    override fun onCaptureFrame(data: ByteArray?, width: Int, height: Int) {

    }


}


